<template>
  <div class="portfolio-position-detail" :class="userCode == clientId?'ismyself':''">
    <div class="portfolio-common-title">
      <span></span>
      <div>详细仓位</div>
      <div class="record" @click.stop.prevent="toRecord">历史调仓记录<i class="iconfont icon-xiangyou"></i></div>
    </div>
    <div class='none-data' v-if="isLoading"><span><i class="iconfont icon-jiazai"></i></span></div>

    <template v-else-if="groupStatue == 1">
      <div class="position-empty" v-if="stockBlocks.length == 0">
        <img class="empty-image" src="~assets/images/portfolio/niuku.png">
        <div class="empty-text">{{error || '暂无数据'}}</div>
      </div>

      <template v-else>
        <div v-for="stocks in stockBlocks">
          <div class="portfolio-position-title"><i class="iconfont" :class="stocks.block_icon"></i>{{stocks.block_name}}
          </div>
          <table class="table">
            <tbody>
            <template v-for="stock in stocks.data">
              <tr>
                <td></td>
                <td :colspan="userCode==clientId?3:5" class="stockRow" @click.stop.prevent="toStock(stock)">
                  <span class="stock_name">{{stock.stock_name}}</span>
                  <span class="stock_code">{{stock.market_code}}{{stock.stock_code}}</span>
                </td>
                <td colspan="2" v-if="userCode==clientId">
                  <span>持仓周期:</span><span class="hold_days">{{stock.hold_days}}</span><span>天</span>
                </td>
              </tr>
              <tr>
                <td></td>
                <td>
                  <span class="last_price color-red">{{stock.last_price}}</span>
                  <span>现价</span>
                </td>
                <td>
                  <span class="cost_price">{{stock.keep_cost_price}}</span>
                  <span>成本价</span>
                </td>
                <td>
                  <span class="position">{{stock.position}}%</span>
                  <span>仓位</span>
                </td>
                <td>
                  <span class="profit" :class="stock.income_balance<0?'loss':'earn'">{{stock.income_balance>0?'+':''}}{{stock.income_balance}}</span>
                  <div class="profit_text">盈亏(
                    <div class="profit_percent" :class="stock.income_balance<0?'loss':'earn'">{{stock.income_balance<0
                      ||
                      stock.profitPercent=="--"?'':'+'}}{{stock.profitPercent}}%
                    </div>
                    )
                  </div>
                </td>
                <td v-if="userCode==clientId">
                  <div class="simusell" @click.stop.prevent="toSell(stock)" >模拟<br>卖出
                  </div>
                </td>
              </tr>
            </template>
            <tr>
              <td></td>
              <td :colspan="userCode==clientId?5:4">
                <div class="progress">
                  <div class="progress-bar progress-bar-info" :style="{width: stocks.blockRate+'%'}"></div>
                </div>
                <span>占比</span><span class="proportion">{{stocks.blockRate}}%</span>
              </td>
            </tr>
            </tbody>
          </table>
        </div>

        <div class="portfolio-position-title"><i class="iconfont icon-qian"></i>现金</div>
        <table class="table">
          <tbody>
          <tr>
            <td></td>
            <td :colspan="userCode==clientId?5:4" class="avail_balance">{{availBalance}}</td>
          </tr>
          <tr>
            <td></td>
            <td :colspan="userCode==clientId?5:4">
              <div class="progress">
                <div class="progress-bar progress-bar-info" :style="{width: moneyRate+'%'}"></div>
              </div>
              <span>占比</span><span class="proportion">{{moneyRate}}%</span>
            </td>
          </tr>
          </tbody>
        </table>
      </template>
    </template>

    <div class="position-empty" v-else-if="groupStatue == 2">
      <img class="empty-image" src="~assets/images/portfolio/niuku.png" v-if="userCode==clientId">
      <img class="empty-image" src="~assets/images/portfolio/niushiluo.png" v-else>
      <div class="empty-text" v-if="userCode==clientId">哎呀，大王你已于{{year}}年{{month}}月{{day}}日<br>清空了该组合，建议尽快调仓，<br>否则会被系统关停。</div>
      <div class="empty-text" v-else>啥米情况？！<br>该牛人已于{{year}}年<br>{{month}}月{{day}}日清空了该组合</div>
    </div>

    <div class="position-empty" v-else-if="groupStatue == 404">
      <img class="empty-image" src="~assets/images/portfolio/niushiluo.png">
      <div class="empty-text">报告大王！<br>小的发现有不明人士趁乱劫走这页文字<br>劳您点击刷新或检测网络设置</div>
    </div>
    <div class="position-empty" v-else-if="groupStatue == 0">
      <img class="empty-image" src="~assets/images/portfolio/niushiluo.png">
      <div class="empty-text">报告大王！<br>您来晚了一步<br>这个组合已经被关停了</div>
    </div>
    <div class="position-empty" v-else>
      <img class="empty-image" src="~assets/images/portfolio/niuku.png">
      <div class="empty-text" v-if="error == ''">报告大王！<br>小的发现有不明人士趁乱劫走这页文字<br>劳您点击刷新或检测网络设置</div>
      <div class="empty-text" v-else>{{error}}</div>
    </div>
  </div>
</template>

<script>
  import  _ from 'underscore'
  import CommonUtil from 'common/common.util'
  import Constant from 'common/constant'
  import RemoteDAO from 'common/remoteDAO'
  import LocalDAO from 'common/localDAO'

  export default {
    name: 'PositionDetail',
    data () {
      return {
        isLoading: true,
        error: '',
        testData: 'testData',
        moneyRate: 100,
        year:'-',//清仓年
        month:'-',//清仓月
        day:'-',//清仓日
        stockBlocks: []
      }
    },
    props: {
      userCode: {type: String},
      clientId: {type: String},
      groupId: {type: String},
      availBalance: {type: Number},
      totalBalance: {type: Number},
      groupStatue: {type: Number},
      groupName: {type: String},
      createDate: {type: String},
      emptyDate :{type: Number}
    },
    created: function () {
      this.fetchData();
    },
    updated:function(){
        if(typeof this.emptyDate !="undefined" && this.emptyDate != 0){
          var date = this.emptyDate+"";
          this.year = Number(date.substring(0,4));
          this.month = Number(date.substring(4,6));
          this.day = Number(date.substring(6,8));
        }
    },
    watch: {
      '$route.query.groupId' (to, from) {
        //跳转相同页面，组件不重新构建，无法调用created,故需监听
        this.fetchData()
      }
    },
    methods: {
      fetchData: function () {
        var self = this;
        //组合持仓
        self.isLoading = true;
        RemoteDAO.callJCL11141(self.clientId, self.groupId, 0, 10, function (response) {
          if (Number(response.error) === 0) {
            var stockList = response.data.body.holders;
            self.stockBlocks = self.groupByBlock(stockList, self.totalBalance);
          } else {
            self.error = response.data;
            self.stockBlocks = [];
          }
          self.isLoading = false;

          //更新分享数据
          var data = {
            stockBlocks: self.stockBlocks,
            group_statue: self.groupStatue,
            total_balance:self.totalBalance,
            avail_balance:self.availBalance,
            describe: self.error,
            isLoading: self.isLoading,
            year:self.year,
            month:self.month,
            day:self.day,
            isMyself:false
          };
          var shareGroup = LocalDAO.getShareGroup();
          shareGroup.position_data = data;
          LocalDAO.setShareGroup(shareGroup);
        });
      },
      /**
       * 对持仓股票根据版块进行分组
       * @param stockList
       * @param totalBalance
       * @returns {Array}
       */
      groupByBlock: function (stockList, totalBalance) {
        var self = this;
        var map = {};
        var stockBlocks = [];
        self.moneyRate = 100;
        for (var i = 0; i < stockList.length; i++) {
          var stock = stockList[i];
          var last_price = Number(stock.last_price), keep_cost_price = Number(stock.keep_cost_price);
          stock.profitPercent = keep_cost_price <= 0 ? "--" : ((last_price - keep_cost_price) / keep_cost_price * 100).toFixed(2);
          stock.market_code = CommonUtil.getMarketCode(stock.exchange_type);
          stock.last_price = CommonUtil.toFixed(stock.last_price, 2);
          stock.keep_cost_price = CommonUtil.toFixed(stock.keep_cost_price, 2);
          stock.position = CommonUtil.toFixed(stock.position, 2);
          stock.income_balance = CommonUtil.toFixed(stock.income_balance, 2);

          if (!map[stock.block_name]) { //若该板块组未生产则生成
            stockBlocks.push({ //板块初始化
              block_name: stock.block_name,//板块名
              block_icon: Constant.BLOCK[stock.block_name],//板块图标
              position: Number(stock.position),//板块持仓
              cost: Number(stock.last_price) * Number(stock.current_vol),//板块花费
              data: [stock]//板块股票数组
            });
            map[stock.block_name] = stock.block_name;//生产一个板块组标识
          } else {
            for (var j = 0; j < stockBlocks.length; j++) { //遍历板块股票组的数组
              var stocks = stockBlocks[j];
              if (stocks.block_name == stock.block_name) {//股票板块名等于板块组的板块名则，改股票加入该组
                stocks.position += Number(stock.position);
                stocks.cost += Number(stock.last_price) * Number(stock.current_vol);
                stocks.data.push(stock);
                break;
              }
            }
          }
        }

        _.each(stockBlocks, function (stocks, index) { //遍历生产好的版块数组计算现金占比和每个版块的占比
          stocks.blockRate = CommonUtil.toFixed(Number(stocks.cost) / totalBalance * 100, 2);
          self.moneyRate -= stocks.blockRate;
        });
        self.moneyRate = CommonUtil.toFixed(self.moneyRate, 2);

        console.log("股票板块分组stockBlocks:", stockBlocks);
        return stockBlocks;
      },
      /**
       * 跳转股票行情
       */
      toStock(stock){
        RemoteDAO.callStockLive(stock.market_code + stock.stock_code, "ordinary", "1", function () {});
      },
      toRecord(){
        this.$router.push({
          path: '/records',
          query: {type: 2, userCode: this.clientId, id: this.groupId, name: this.groupName, date: this.createDate}
        })
      },
      toSell(stock){
        this.$router.push({
          path: '/trade/sellout',
          query: {
            menuId: '2',
            groupId: this.groupId,
            stockCode: stock.stock_code,
            stockName: stock.stock_name,
            marketCd: stock.exchange_type
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
